package org.pblue.tumblarity.view;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.pblue.appengine.AppengineDataException;
import org.pblue.tumblarity.controller.EditBlog;
import org.pblue.tumblarity.data.bean.Tumblelog;


@SuppressWarnings("serial")
public class FollowersView extends HttpServlet {
  
  public static final String TEMPLATE = "/track.jsp";
  public static final String COMPONENT = "followers";
  public static final String URI_REDIRECT = "/";
  public static final String REQUEST_ATTR_TUMBLELOG_ID = "tumblelogId";
  
  @SuppressWarnings("unchecked")
  @Override
  protected void service(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
    HttpSession session = pRequest.getSession();
    
    pRequest.setAttribute(EditBlog.ATTR_ERRORS, session.getAttribute(EditBlog.ATTR_ERRORS));
    pRequest.setAttribute(EditBlog.ATTR_MESSAGE, session.getAttribute(EditBlog.ATTR_MESSAGE));
    
    session.removeAttribute(EditBlog.ATTR_EMAIL);
    session.removeAttribute(EditBlog.ATTR_TUMBLELOG_NAME);
    session.removeAttribute(EditBlog.ATTR_ERRORS);
    session.removeAttribute(EditBlog.ATTR_MESSAGE);
    
    List<String> uriComponents = (List<String>) pRequest.getAttribute(UrlMappingFilter.REQUEST_ATTR_COMPONENT_LIST);
    
    if (uriComponents.size() > 1) {
      String email = uriComponents.get(1);
      
      String tumblelogName = null;
      if (uriComponents.size() > 2) {
        tumblelogName = uriComponents.get(2);
      }
      
      try {
        Tumblelog tumblelog = Tumblelog.get(email, tumblelogName);
        if (tumblelog != null && tumblelog.authenticateRequest(pRequest)) {
          pRequest.setAttribute(EditBlog.ATTR_EMAIL, email);
          pRequest.setAttribute(EditBlog.ATTR_TUMBLELOG_NAME, tumblelogName);
          pRequest.setAttribute(REQUEST_ATTR_TUMBLELOG_ID, tumblelog.getId());

          RequestDispatcher rd = pRequest.getRequestDispatcher(TEMPLATE);
          rd.forward(pRequest, pResponse);
          return;
        }
      } catch (AppengineDataException e) {
      }

      session.setAttribute(EditBlog.ATTR_EMAIL, email);
      session.setAttribute(EditBlog.ATTR_TUMBLELOG_NAME, tumblelogName);

    }

    pResponse.sendRedirect(URI_REDIRECT);
      
  }
  
}
